﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonFramework.Storage.Cache;
using Xinkui.Common;
using System.Threading;

namespace Xinkui.WebModel.Cache {
    public class CacheProxy {
        public static ICache _CacheInstance = CommonFramework.Storage.Cache.CacheManager.CreateCache("Apsoto_Common");
        const int WaitMillseconds = 500;
        public static void Add<T>(string key, T cahceView) {
            lock (key) {
                _CacheInstance.Add<T>(key, cahceView);
            }
        }

        public static void Set<T>(string key, T cacheView) {
            lock (key) {
                _CacheInstance.Set<T>(key, cacheView);
            }
        }

        public static void Remove(string key) {
            lock (key) {
                _CacheInstance.Remove(key);
            }
        }

        public static T Get<T>(string key, Func<T> callback) {
            var temp = _CacheInstance.Get<T>(key);
            if (temp != null) return temp;
            if (Monitor.TryEnter(key, WaitMillseconds)) {
                try {
                    if ((temp = _CacheInstance.Get<T>(key)) == null) {

                        temp = callback();
                        Add<T>(key, temp);
                        return temp;

                    }
                    else {
                        return temp;
                    }
                }
                catch {
                    return default(T);
                }
                finally {
                    Monitor.Exit(key);
                }
            }
            return default(T);
        }
    }
}
